package com.project.controller.web;

import com.project.common.utils.Constants;
import com.project.common.utils.ExcelUtil;
import com.project.common.utils.MyPageHelper;
import com.project.entity.InternInfo;
import com.project.entity.StudentInfo;
import com.project.entity.User;
import com.project.myBeans.InternInfoDetail;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.myBeans.StudentInfoDetail;
import com.project.service.*;
import com.project.service.base.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.project.controller.web.StudentController.*;

/**
 * @Author: TateBrown
 * @date: 2018/5/26 18:22
 * @param:
 * @return:
 */
@EnableAutoConfiguration
@RestController
@RequestMapping("/internInfo")
@Api(description = "实习信息相关操作", value = "interninfo")
public class InternInfoController extends BaseService{
    @Autowired
    private UserService userService;

    @Autowired
    private InternInfoService internInfoService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private ImagesService imagesService;

    /**
     * TateBrown 2018年5月26日
     *
     * @param internInfo
     * @return
     */
    @ApiOperation("模糊搜索分页显示")
    @PostMapping("/findByCondition")
    public R findByCondition(@RequestBody InternInfo internInfo){
        try{
             if(internInfo.getPageIndex()>0)
                 internInfo.setPageIndex(internInfo.getPageIndex()-1);
            List<InternInfo> internInfos=internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails=new ArrayList<>();
            for(InternInfo internInfo1:internInfos){
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            return R.ok("查询成功").put("data",internInfoDetails).put("total", MyPageHelper.getTotal(internInfoDetails));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param user
     * @return
     */
    @ApiOperation("根据学生userId批量获取实习信息+分页")
    @PostMapping("/findBatchByUserid")
    public R findBatchByUserid(@RequestBody User user){
        try{
            //1. 先找到学生信息表
            StudentInfo studentInfo = studentInfoService.findOneByUserId(user.getId());
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo.getId());
            //设置分页参数
            internInfo.setPageIndex(user.getPageIndex());
            internInfo.setPageSize(user.getPageSize());
            if (internInfo.getPageIndex() > 0) // 若需要分页
                internInfo.setPageIndex(internInfo.getPageIndex() - 1);
            List<InternInfo> internInfos = internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails = new ArrayList<InternInfoDetail>();
            for (InternInfo internInfo1 : internInfos) {
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            return R.ok("查询成功").put("data",internInfoDetails).put("total",MyPageHelper.getTotal(internInfoDetails));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param internInfo
     * @return
     */
    @ApiOperation("根据学生userId批量获取实习信息+分页")
    @PostMapping("/findAll")
    public R findAll(@RequestBody InternInfo internInfo){
        try{
            if (internInfo.getPageIndex() > 0) // 若需要分页
                internInfo.setPageIndex(internInfo.getPageIndex() - 1);
            List<InternInfo> internInfos = internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails = new ArrayList<InternInfoDetail>();
            for (InternInfo internInfo1 : internInfos) {
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            return R.ok("查询成功").put("data",internInfoDetails).put("total",MyPageHelper.getTotal(internInfoDetails));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序错误");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param internInfo
     * @return
     */
    @ApiOperation("根据id更新实习信息")
    @PostMapping("/modify")
    public R modity(@RequestBody InternInfo internInfo){
        ResponseBean responseBean = new ResponseBean();
        try{
            if(processSuccessDeleteUpdate(internInfoService.modify(internInfo)))
                return R.ok("修改成功");
                else{
                return R.error("修改失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }

    }

    /**
     * TateBrown 2018年5月26日
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id删除实习信息")
    @GetMapping("/remove/{id}")
    public R remove(@PathVariable("id") Integer id){
        try{
            if(internInfoService.delete(id)>0){
                return R.ok("删除成功");
            }else{
                return R.error("删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param internInfo
     * @return
     */
    @ApiOperation("添加实习信息")
    @PostMapping("/add")
    public R add(@RequestBody InternInfo internInfo){
        try{
            if(processSuccessDeleteUpdate(internInfoService.add(internInfo)))
                return R.ok("添加成功");
            else
                return R.error("添加失败");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param id
     * @return
     */
    @ApiOperation("根据实习id查找实习信息")
    @GetMapping("/modify")
    public R findOne(@PathVariable("id") Integer id){
        try{
            return R.ok("获取成功").put("data",internInfoService.findDetailById(id));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param studentInfo
     * @return
     */
    @ApiOperation("根据学生表条件模糊查找每一个学生最有效的一条信息（有现在实习信息的优先）")
    @PostMapping("/findBatchByCondition2")
    public R findBatchByCondition2(@RequestBody StudentInfo studentInfo){
        if(studentInfo.getPageIndex()>0){
            studentInfo.setPageIndex(studentInfo.getPageIndex()-1);
        }
        List<InternInfoDetail> internInfoDetailList=new ArrayList<>();
        try{
            List<StudentInfo> studentInfoList=studentInfoService.findBatchByCondition(studentInfo);
            getInternInfoDetail(internInfoDetailList,studentInfoList);
            return R.ok("获取成功").put("data",internInfoDetailList).put("total",MyPageHelper.getTotal(internInfoDetailList));
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param internInfoDetail
     * @return
     */
    @ApiOperation("根据学生表实习信息表条件模糊查找")
    @PostMapping("/findBatchByCondition3")
    public R findBatchByCondition3(@RequestBody InternInfoDetail internInfoDetail){
        int pageIndex=internInfoDetail.getPageIndex()-1;
        int pageSize=internInfoDetail.getPageSize();
        List<InternInfoDetail> internInfoDetailList=new ArrayList<>();
        try {
            if (internInfoDetail.getStudentInfoDetail() != null) {
                if (internInfoDetail.getStudentInfoDetail().getStudentInfo() != null) {
                    //首先根据学生信息表的条件进行筛选
                    StudentInfo studentInfo = internInfoDetail.getStudentInfoDetail().getStudentInfo();
                    //根据学生信息表筛选出符合条件的学生信息表记录
                    List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
                    List<Integer> snoList = new ArrayList<>();
                    for (StudentInfo studentInfo1 : studentInfoList) {
                        snoList.add(studentInfo1.getId());
                    }
                    InternInfo internInfo = internInfoDetail.getInternInfo();
                    internInfo.setSnoList(snoList);
                    internInfo.setPageSize(pageSize);
                    internInfo.setPageIndex(pageIndex);
                    List<InternInfo> internInfoList = internInfoService.findByCondition(internInfo);
                    for (InternInfo internInfo1 : internInfoList) {
                        internInfoDetailList.add(internInfoService.findDetailById(internInfo1.getId()));
                    }
                    return R.ok("查询成功").put("data",internInfoDetailList).put("total",MyPageHelper.getTotal(internInfoDetailList));
                }else{
                    return R.error("缺少学生详细信息");
                }
            }
            else {
                return R.error("缺少学生详细信息");
            }

        }catch (Exception e) {
            e.printStackTrace();
            return R.error();
                }
            }
    /**
     * TateBrown 2018年5月26日
     *
     * @param userId
     * @return
     */
    @ApiOperation("根据userid判断是否处于审核状态")
    @PostMapping("/findIsUnderReview/{userId}")
    public R findIsUndeerReview(@PathVariable("userid") Integer userId){
        try{
            StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo.getId());
            if(internInfoService.checkIsUnderReview(internInfo)){
                return R.ok("处于审核流程");
            }else{
                return R.ok("不处于审核流程");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param studentInfo
     * @param advisorId
     * @return
     */
    @ApiOperation("教师根据学生表条件模糊查找每个学生最有效的一条信息（有现在实习信息优先显示) 显示学校实习指导老师或新实习指导老师（指导老师更换）时的指导老师")
    @PostMapping("/findBatchByConditionForTeacher/{advisorId}")
    public R findBatchByCondition4(@RequestBody StudentInfo studentInfo, @PathVariable Integer advisorId){

            if(studentInfo.getPageIndex()>0){
                studentInfo.setPageIndex(studentInfo.getPageIndex()-1);
            }
            List<InternInfoDetail> internInfoDetailList=new ArrayList<>();
            try{
                //根据学生信息表筛选出符合条件的学生信息表记录
                //1. 导师申请中
                studentInfo.setInternadvisor(advisorId);
                studentInfo.setAdvisestate(1);//导师申请中
                List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);

                //2. 导师指导中
//            studentInfo.setInternadvisor(advisorId);
                studentInfo.setAdvisestate(2);//导师指导中
                List<StudentInfo> studentInfoList2 = studentInfoService.findBatchByCondition(studentInfo);

                //3. 指导老师更换中
                studentInfo.setInternadvisor(null);
                studentInfo.setNewadvisor(advisorId);
                studentInfo.setAdvisestate(4);//导师更换中
                List<StudentInfo> studentInfoList3 = studentInfoService.findBatchByCondition(studentInfo);

                studentInfoList.addAll(studentInfoList2);
                studentInfoList.addAll(studentInfoList3);

                getInternInfoDetail(internInfoDetailList, studentInfoList);
                return R.ok("查询成功").put("data",internInfoDetailList).put("total",MyPageHelper.getTotal(internInfoDetailList));
            } catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param classId
     * @param response
     * @return
     */
    @ApiOperation("生成实习安排报表")
    @GetMapping("/generatorInternReport/{classId}")
    public R generatorInternReport(@PathVariable("classId")Integer classId,HttpServletResponse response){
        try(OutputStream outputStream=response.getOutputStream()){
            StudentInfo studentInfo=new StudentInfo();
            studentInfo.setClassid(classId);
            List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
            List<Integer> userIds = new ArrayList<>();
            for (StudentInfo studentInfo1 : studentInfoList) {
                userIds.add(studentInfo1.getUserid());
            }
            //绝对路径
//            String rootPath = Util.getWebRootURL(this);

//            File file = new File(rootPath + "/" + "reportTemp.xls");
//            Workbook wb = ExcelUtil.importInterInfoData(file, "test", internInfoService.findBatchByUserIds(userIds), (short)5);
            Workbook wb = ExcelUtil.importInterInfoData("test", internInfoService.findBatchByUserIds(userIds), (short) 5);
            response.reset();
            long filename = System.currentTimeMillis();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = df.format(filename);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            wb.write(outputStream);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    private void getInternInfoDetail(List<InternInfoDetail> internInfoDetailList, List<StudentInfo> studentInfoList) throws Exception {
        for (StudentInfo studentInfo1 : studentInfoList) {
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo1.getId());
            switch (studentInfo1.getState()) {
                /**
                 * 未实习 实习信息表一定为空 只需添加学生信息表信息
                 */
                case STUDENTSTATE_NO: {
                    InternInfoDetail internInfoDetail1 = new InternInfoDetail();
                    StudentInfoDetail studentInfoDetail = studentInfoService.findDetailById(studentInfo1.getId());
                    internInfoDetail1.setStudentInfoDetail(studentInfoDetail);
                    internInfoDetailList.add(internInfoDetail1);
                    break;
                }
                /**
                 * 实习申请中 说明实习信息表中一定只有一条记录处于审核流程中
                 */
                case STUDENTSTATE_APPLY: {
                    internInfo = internInfoService.findOneBySnoAndReview(internInfo);
                    internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
                    break;
                }
                /**
                 * 实习中显示正在实习的记录
                 */
                case STUDENTSTATE_ING: {
                    internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
                    //查找正在实习的信息（仅有一条）
                    internInfo = internInfoService.findOneBySnoAndOragattr(internInfo);
                    internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
                    break;
                }
                /**
                 * 实习变更中的显示实习中和想要去实习
                 */
                case STUDENTSTATE_CHANGE: {
                    internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
                    //查找正在实习的信息（仅有一条）
                    internInfo = internInfoService.findOneBySnoAndOragattr(internInfo);
                    InternInfoDetail internInfoDetail = internInfoService.findDetailById(internInfo.getId());

                    //查找审核中的实习信息也就是提交的变更的实习信息
                    InternInfo condition = new InternInfo();
                    condition.setSno(studentInfo1.getId());
                    condition = internInfoService.findOneBySnoAndReview(condition);
                    internInfoDetail.setChange(condition);
                    internInfoDetailList.add(internInfoDetail);
                    break;
                }
                default:
            }
        }
    }
}
